<template>
  <div>
    <Spin :spinning="loading" tip="Loading...">
      <FilterTable ref="picTable" :columns="picColumns" :dataSource="picFiles" :params="picParams" height="auto" :datakey="'records'" :isSelectColumn="false" :isToperInfo="false" :isColumnFilter="false" :isPagination="false" :onRowSelectChange="selectChange" :onColumnsChange="picColumns => (this.picColumns = picColumns)">
      </FilterTable>
    </Spin>

    <el-upload ref="upload" :action="this.uploadAction" accept=".jpg, .jpeg, .png, .pdf" multiple :data="uploadData" :limit="this.picLimit" :show-file-list="false" :headers="headers" :file-list="this.picFiles" :before-upload="handleBeforeUpload" :on-success="handleSuccess" :on-error="handleError" :on-exceed="handleExceed">
      <el-button size="small" type="primary">点击上传</el-button>
    </el-upload>

    <!-- 查看凭证 -->
    <el-image-viewer :url-list="picList" v-show="imagesViewShow" :on-close="closeImagesViewer"></el-image-viewer>

    <div class="dialogBottmView">
      <el-button @click="closeDialog">返回</el-button>
    </div>
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import { getFileGroup, deleteZcPicFile } from '@/api/graphic/catalogue/index';
import config from '@/assets/js/config';
import ElImageViewer from 'element-ui/packages/image/src/image-viewer';
import moment from 'moment';
import axios, { getConfigHeaders } from '@/api/fetch';

export default {
  name: 'ImageZc',
  mixins: [dictionary],
  components: { ElImageViewer },
  props: {
    rowData: { type: Object, default: () => ({}) }
  },
  data() {
    return {
      uploadAction: config.uploadUrl + '/api/file/v1/file/upload',
      headers: getConfigHeaders(),
      uploadPrefix: config.uploadUrl,// 附件上传前缀
      picColumns: this.createPicTable(),
      picFiles: [],
      picParams: { xtdjid: '', xtfjlx: 'tt_graphic_assembly_info' },
      loading: false,
      picList: [],
      imagesViewShow: false,
      picLimit: 1,
      uploadData: { bucketType: 'private', fileName: '' }
    };
  },
  created() {
    this.init(this.rowData);
  },
  methods: {
    handleError(err, file, fileList) {
      this.$notify.error('上传失败：' + err);
    },
    handleExceed(files, fileList) {
      this.$notify.warning('图片最多只可上传1张！');
    },
    // 上传成功回调
    handleSuccess(response, file, fileList) {
      this.loading = true;
      //let res = this.getPicUrl(response.data);
      setTimeout(() => {
        this.getPicUrl(response.data.url).then(res => {
          let data = { index: '', name: '', url: '', xtwjmc: '', xtwjlj: '' };
          this.$set(data, 'index', this.picFiles.length);
          this.$set(data, 'name', file.name);
          this.$set(data, 'xtwjmc', file.name);
          this.$set(data, 'xtwjlj', response.data.url);
          this.$set(data, 'url', res);
          if (this.getFileType(data.name) != 'pdf') {
            this.picList.push(data.url);
          }
          this.picFiles.push(data);
        });
        this.$emit('picFiles', this.picFiles);
        this.$notify.success({ title: '提示信息', message: '上传成功!' });
      }, 300);
      this.loading = false;
    },
    handleBeforeUpload(file) {
      let fileName = file.name.substring(0, file.name.lastIndexOf('.')) + `-${moment().format('YYYY-MM-DD')}`;
      this.uploadData.fileName = fileName;
      console.info(this.uploadData);
      this.loading = true;
      const isLt20M = file.size / 1024 / 1024 <= 20;
      if (!isLt20M) {
        this.$notify.warning('上传的图片大小不能超过 20MB!');
      }
      this.loading = false;
      return isLt20M;
    },
    closeImagesViewer() {
      this.imagesViewShow = false;
    },
    selectChange(val) {
      console.log('val', val);
      this.rowSelectData = val;
    },
    init(data) {
      this.loading = true;
      getFileGroup({ "xtdjid": data.assemblyId, "xtfjlx": "tt_graphic_assembly_info" }).then(response => {
        this.picFiles = response.data;
        this.picFiles.forEach(x => {
          x.xtwjmc = x.name;
          x.xtwjlj = x.url;
          this.getPicUrl(x.url).then(res => {
            x.url = res;
            if (this.getFileType(x.name) != 'pdf') {
              this.picList.push(res);
            }
          });
        });
        this.loading = false;
      });
    },

    createPicTable() {
      return [
        {
          title: '序号', dataIndex: 'index', width: 70, sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作', dataIndex: 'column-action', width: 150, align: 'center',
          render: props => {
            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.deletePic(props.row)}>
                  删除
                </el-button>
              </div>
            );
          }
        },

        {
          title: '图片', dataIndex: 'name', align: 'center',
          render: p => {
            let fileType = this.getFileType(p.row.name);
            return fileType == 'pdf' ? (
              <div class="imgfile">
                <div class="pdfdiv"></div>
                <a href={p.row.url} target="_blank">{p.row.name}</a>
              </div>
            ) :
              (
                <div class="imgfile">
                  <img src={p.row.url} onClick={() => { this.imagesViewShow = true; }} alt="" />
                  <a href={p.row.url} target="_blank">{p.row.name}</a>
                </div>
              );
          }
        }
      ]
    },

    closeDialog(param) {
      this.$emit('close', { visible: false, type: param });
    },

    async getPicUrl(url) {
      let actionUrl = this.uploadPrefix + '/api/file/download/url?fileUrl=' + url;
      let res = await axios.post(actionUrl);
      return res.data;
    },
    async deletePic(val) {
      this.$confirm('确定删除此文件吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let picIndex = 0;
        if (val.id != null && val.id > 0) {
          const res = await deleteZcPicFile({ id: val.id, partId: this.rowData.id });
          if (res.resultCode === 200) {
            this.$refs.picTable.$refs.pageTable.EXECUTE_DELETE([val]);
            this.picFiles.forEach(x => {
              this.$set(x, 'index', picIndex++);
            });
            this.$notify.success({ title: '提示信息', message: '删除成功!' });
          }
        } else {
          this.$refs.picTable.$refs.pageTable.EXECUTE_DELETE([val]);
          this.picFiles.forEach(x => {
            this.$set(x, 'index', picIndex++);
          });
          this.$notify.success({ title: '提示信息', message: '删除成功!' });
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },

    getFileType(fileName) {
      let fileType = fileName.substring(fileName.lastIndexOf('.') + 1, fileName.length);
      return fileType;
    }
  }
};
</script>

<style>
.el-table__body-wrapper {
  overflow-x: auto;
  position: static;
}
.el-image {
  float: left;
  margin-left: 130px;
}
/* .el-image a {
    float: left;
} */
.imgfile {
  height: 60px;
  line-height: 60px;
  overflow: hidden;
}
.imgfile a {
  float: left;
  margin-left: 20px;
}
.imgfile img {
  float: left;
  margin-left: 30%;
  width: 100px;
  height: 100%;
  object-fit: cover;
}
.pdfdiv {
  float: left;
  margin-left: 30%;
  width: 100px;
  height: 100%;
  object-fit: cover;
}
</style>
